package com.whiteape.book.presenter;


import com.whiteape.book.contract.BookReadContract;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.WebMediaManager;
import com.whiteape.book.core.page.TxtChapter;
import com.whiteape.book.model.bo.ChapterContentBo;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.SiteSourceBean;
import com.whiteape.book.ui.base.RxPresenter;
import com.whiteape.book.utils.LogUtils;
import com.whiteape.book.utils.RxUtils;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by newbiechen on 17-5-16.
 */

public class BookReadPresenter extends RxPresenter<BookReadContract.View>
        implements BookReadContract.Presenter {
    private static final String TAG = "BookReadPresenter";

    private Subscription mChapterSub;

    @Override
    public void loadCatalog(SiteSourceBean siteSourceBean, CollectionMediaBean bookBean) {
        LogUtils.d("loadWebCatalog");
        String bookChapterListUrl = bookBean.getCatalogUrl();
        Disposable disposable = WebMediaManager.getInstance()
                .getCatalog(siteSourceBean, bookBean)
//                .doOnSuccess(new Consumer<List<MediaChapterBean>>() {
//                    @Override
//                    public void accept(List<MediaChapterBean> bookChapterBean) throws Exception {
//                        //进行设定BookChapter所属的书的id。
//                        LogUtils.d("loadWebCatalog, accept, bookChapterBean is " + bookChapterBean);
//                        for (MediaChapterBean bookChapter : bookChapterBean) {
//                            bookChapter.setId(MD5Utils.strToMd5By16(bookChapter.getLink()));
//                            bookChapter.setLink(bookChapter.getLink());
//                            bookChapter.setMediaId(bookBean.getId());
//                        }
//                    }
//                })
                .compose(RxUtils::toSimpleSingle)
                .subscribe(
                        beans -> {
                            LogUtils.d("loadWebCatalog, onSuccess, beans is " + beans);
                            mView.showCatalog(beans);
                        }
                        ,
                        e -> {
                            //TODO: Haven't grate conversation method.
                            LogUtils.e(e);
                            e.printStackTrace();

                        }
                );
        addDisposable(disposable);
    }

    @Override
    public void loadChapter(SiteSourceBean siteSourceBean, CollectionMediaBean collectionMediaBean, String bookId, List<TxtChapter> bookChapters) {
        int size = bookChapters.size();

        //取消上次的任务，防止多次加载
        if (mChapterSub != null) {
            mChapterSub.cancel();
        }

        List<Single<List<ChapterContentBo>>> chapterInfos = new ArrayList<>(bookChapters.size());
        ArrayDeque<String> titles = new ArrayDeque<>(bookChapters.size());

        // 将要下载章节，转换成网络请求。
        for (int i = 0; i < size - 1; ++i) {
            TxtChapter bookChapter = bookChapters.get(i);
            // 网络中获取数据
            Single<List<ChapterContentBo>> chapterInfoSingle = WebMediaManager.getInstance()
                    .getBookChapterContent(siteSourceBean, collectionMediaBean, bookChapter.getLink(), bookChapters.get(i + 1).getLink());

            chapterInfos.add(chapterInfoSingle);

            titles.add(bookChapter.getTitle());
        }


        Single.concat(chapterInfos)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Subscriber<List<ChapterContentBo>>() {
                            String title = titles.poll();

                            @Override
                            public void onSubscribe(Subscription s) {
                                s.request(Integer.MAX_VALUE);
                                mChapterSub = s;
                            }

                            @Override
                            public void onNext(List<ChapterContentBo> chapterContentBoList) {
                                //存储数据
                                StringBuilder sb = new StringBuilder();
                                for (ChapterContentBo chapterContentBo : chapterContentBoList) {
                                    sb.append(chapterContentBo.getContent());

                                }
//                                MediaStorageManager.getInstance().saveChapterInfo(
//                                        bookId, title, sb.toString()
//                                );
                                addDisposable(MediaStorageManager.getInstance()
                                        .saveChapterInfoInRx(bookId, title, sb.toString()));


                                mView.finishChapter();
                                //将获取到的数据进行存储
                                title = titles.poll();
                            }

                            @Override
                            public void onError(Throwable t) {
                                //只有第一个加载失败才会调用errorChapter
                                if (bookChapters.get(0).getTitle().equals(title)) {
                                    mView.errorChapter();
                                }
                                LogUtils.e(t);
                            }

                            @Override
                            public void onComplete() {
                            }
                        }
                );
    }

    @Override
    public void detachView() {
        super.detachView();
        if (mChapterSub != null) {
            mChapterSub.cancel();
        }
    }

}
